package cn.edu.sdjzu.cs.dingcan.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.edu.sdjzu.cs.dingcan.entity.OrderItem;
import cn.edu.sdjzu.cs.dingcan.utils.JdbcUtils;


public class OrderItemDao {

	private final QueryRunner queryRunner;
	private final String insertOrderSql = "INSERT order_item (order_id, food_id, food_count) VALUES(?, ?, ?)";
	
	public OrderItemDao() {
		this.queryRunner = JdbcUtils.getQueryRunner();
	}

	/**
	 * 插入一条订单明细条目
	 * 
	 * @param orderId   所属订单id
	 * @param orderItem 明细条目
	 * @throws SQLException
	 */
	public void add(Long orderId, OrderItem orderItem) throws SQLException {
		this.queryRunner.update(insertOrderSql, orderId, orderItem.getFood().getId(), orderItem.getCount());		
	}

	/**
	 * 批量插入一条订单的多个明细条目
	 * 
	 * @param orderId    所属订单id
	 * @param orderItems 明细条目list
	 * @throws SQLException
	 */
	public void add(Long orderId, List<OrderItem> orderItems) throws SQLException {
		Object[][] params = getBatchInsertParasm(orderId, orderItems);
		this.queryRunner.batch(insertOrderSql, params);		
	}

	/**
	 * 批量插入一条订单的多个明细条目，提供数据库连接参数，用于事务
	 * 
	 * @param conn       DB connection
	 * @param orderId    所属订单id
	 * @param orderItems 明细条目list
	 * @throws SQLException
	 */
	public void add(Connection conn, Long orderId, List<OrderItem> orderItems) throws SQLException {
		Object[][] params = getBatchInsertParasm(orderId, orderItems);
		this.queryRunner.batch(conn, insertOrderSql, params);		
	}

	private Object[][] getBatchInsertParasm(Long orderId, List<OrderItem> orderItems) {
		Object[][] params = new Object[orderItems.size()][3];
		for(int i = 0; i < orderItems.size(); i++) {
			params[i][0] = orderId;
			params[i][1] = orderItems.get(i).getFood().getId();
			params[i][2] = orderItems.get(i).getCount();
		}
		return params;
	}
	
	/**
	 * 根据订单id获取明细条目
	 * 
	 * @param orderId
	 * @return
	 * @throws SQLException
	 */
	public List<OrderItem> findByOrderId(Long orderId) throws SQLException {
		String sql = "SELECT * FROM order_item where order_id = ?";
		return this.queryRunner.query(sql, new BeanListHandler<OrderItem>(
				OrderItem.class), orderId);
	}
}
